package com.ruoyi.wechat.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author: YinHeng
 * @Description:
 * @DateTime: 2022/8/31 17:00
 */
@Component
public class RedisHelper {

    private static String HOST;
    private static Integer PORT;
    private static String PASSWORD;

    @Autowired
    public void init(@Value("${spring.redis.host}") String host,
                     @Value("${spring.redis.port}") Integer port,
                     @Value("${spring.redis.password}") String password) {
        RedisHelper.HOST = host;
        RedisHelper.PORT = port;
        RedisHelper.PASSWORD = password;
    }

    private static JedisPool jedisPool = null;


    public static JedisPool getPool() {

        if (jedisPool != null) {
            return jedisPool;
        }

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(500);
        config.setMaxIdle(500);
        config.setBlockWhenExhausted(true);
        config.setTestOnBorrow(false);
        config.setTestOnReturn(false);
        jedisPool = new JedisPool(config, HOST, PORT,null,PASSWORD);

        return jedisPool;
    }

    /**
     * 设置缓存
     * @param key
     * @param seconds
     * @param value
     */
    public static void setEx(String key,Long seconds,String value){
        JedisPool pool = getPool();
        try(Jedis jedis = pool.getResource()){
            jedis.setex(key,seconds,value);
        }
    }

    /**
     * 获取缓存
     * @param key
     * @return
     */
    public static String get(String key){
        JedisPool pool = getPool();
        try(Jedis jedis = pool.getResource()){
            return jedis.get(key);
        }
    }



}
